<template>
    <div class="login-container">
        <img src="../../assets/logo.png" class="logo-box animated zoomInDown" />
        <el-form class="login-form animated zoomInUp" autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left">
            <h3 class="title">S端汽修宝管理后台</h3>
            <el-form-item prop="username">
                <span class="svg-container svg-container_login">
                    <svg-icon icon-class="user" />
                </span>
                <el-input name="username" type="number" maxLength="11" v-model="loginForm.username" placeholder="账号" />
            </el-form-item>
            <el-form-item prop="password">
                <span class="svg-container">
                    <svg-icon icon-class="password"></svg-icon>
                </span>
                <el-input name="password" :type="pwdType" @keyup.enter.native="handleLogin" maxLength="12" v-model="loginForm.password" autoComplete="on"
                    placeholder="请输入密码">
                </el-input>
                <span class="show-pwd" @click="showPwd">
                    <svg-icon icon-class="eye" />
                </span>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" style="width:100%;" :loading="loading" @click.native.prevent="handleLogin">登录</el-button>

            </el-form-item>
            <p class="comText">广州前实网络科技有限公司 © 2018 All Rights Reserved</p>
        </el-form>
    </div>
</template>

<script>
    import {
        isvalidUsername
    } from '@/utils/validate'
    import {
        mapMutations,
        mapGetters
    } from 'vuex'
    import {
        getToken,
        setToken
    } from '@/utils/auth'
    import {
        SUCCESS_REQUEST_STATUS,
        secondDirectory
    } from '@/utils/config.js'
    import Layout from '../../views/layout/Layout'
    //import Cookies from 'js-cookie'
    export default {
        name: 'login',
        data() {
            // 验证用户名
            const validateUsername = (rule, value, callback) => {
                !value ? callback(new Error('账号不能为空')) : value.length < 1 ? callback(new Error('请输入11位数字号码')) :
                    callback()

            }
            // 验证密码 18620169926
            const validatePass = (rule, value, callback) => {
                !value ? callback(new Error('密码不能为空')) : value.length < 6 ? callback(new Error('密码不能少于6位')) :
                    callback()
            }
            return {
                loginForm: {
                    username: '',
                    password: ''
                },
                loginRules: {
                    username: [{
                        required: true,
                        trigger: 'blur',
                        validator: validateUsername
                    }],
                    password: [{
                        required: true,
                        trigger: 'blur',
                        validator: validatePass
                    }]
                },
                rsaKey: null,
                loading: false,
                pwdType: 'password',
                enPassword: '',
            }
        },

        methods: {
            /**
             * 	@desc 密码是否可看
             */
            showPwd() {
                this.pwdType = this.pwdType === 'password' ? '' : 'password'
            },
            /**
             * 	@desc 登录操作
             */
            handleLogin() {
            	let attr = !this.loginForm.username? '账号不能为空': !this.loginForm.password ?  '密码不能为空' : ''
            	if(attr) {
					this.$message({
						type: 'error',
						message: attr
					})
					return
				}
                this.loading = true
                this.$ajax({
					type: 'GET',
					key: 'public_key',
					api: 'public_key'
				}).then(res => {
					this.rsaKey.setPublic(b64tohex(res.data.modulus), b64tohex(res.data.exponent))
					this.enPassword = hex2b64(this.rsaKey.encrypt(this.loginForm.password))
					if (this.enPassword) {
						this.getLogin()
					}
				}).catch(err => {
					this.$message({
						type: 'error',
						message: err.message
					})
					this.loading = false
				})
                
            },
            /**
             * 	@desc 登录接口请求
             */
            getLogin() {
            	this.$ajax({
                    api: 'admin/login',
                    params: {
                        mobile: this.loginForm.username,
                        enPassword: this.enPassword
                    }
                }).then(res => {
                	this.loading = false
                    if (res.status === SUCCESS_REQUEST_STATUS) {
                    	res.data.menuList.forEach(item => {
                    		switch(item.name) {
                    			case '车型':
	                    			item.icon = 'icon-chepai'
									break;
								case '品类':
									item.icon = 'icon-leimupinleifenleileibie'
									break;
								case '商家':
									item.icon = 'icon-msnui-dianpu'
									break;
								case '权限':
									item.icon = 'icon-add-permissions'
									break;
                    		}
                    	})
                        this.setMerchantInfo(res.data.menuList)
                        sessionStorage.setItem('menuList', JSON.stringify(res.data.menuList))
						sessionStorage.setItem('loginId', res.data.admin.id)
						sessionStorage.setItem('loginName', res.data.admin.name)
                        setToken(res.data.admin.mobile)
                        // 设置当前菜单权限
                        this._initMenu(res.data.menuList)
                    }else{
                    	 this.$message({
	                        message: res.data.message,
	                        type: 'error'
	                    });
                    }
                }).catch(err => {
                    this.$message({
                        message: err.message,
                        type: 'error'
                    });
                    this.loading = false

                })
            },
            /**
             * 	@desc  初始化菜单栏
             * 	@param list 登录用户的菜单权限
             */
            _initMenu(list) {
                this.$ajax({
                    api: 'menu/list'
                }).then(res => {
                    let attr = []
                    if (res.status === SUCCESS_REQUEST_STATUS) {
                        let mList = list.map((item) => {
                            return item.functions.split(',')
                        })
                        let menuObj = null
                        list.forEach((item, index) => {
                            menuObj = {
                                index: index,
                                menuUrl: item.menuUrl,
                                title: list[index].name,
                                menu: list[index].functions.split(',')
                            }
                            attr.push(menuObj)
                        })
						sessionStorage.setItem('functionMap', JSON.stringify(res.data.functionMap))
                        this.handleMeunList(res.data.functionMap, attr)
                    }
                })
            },
            /**
             * 	@desc  初始化菜单栏
             * 	@param functionMap 所有权限
             * 	@param adminList 登录用户权限
             */
            handleMeunList(functionMap, adminList) {
            	let neStep = ''
            	let menuList = sessionStorage.getItem('menuList') ? JSON.parse(sessionStorage.getItem('menuList')) : []
                adminList.forEach((item) => {
                    item.menuUrl = item.menuUrl.substring(1, item.menuUrl.length)
                    item.list = item.menu.map(child => {
                        if (child && functionMap[child] != undefined) {
                            return functionMap[child]
                        }
                    })
                    item.list = item.list.filter((i) => {
                        return i != undefined
                    })
                    item.menu = item.menu.filter((i) => {
                        return i != ''
                    })
                })
				console.log(adminList)
				sessionStorage.setItem('adminList', JSON.stringify(adminList)) 
                //this.setSecondDirectory(adminList)
                if(menuList && menuList.length > 0) {
					neStep = menuList[0].menuUrl
				}
                this.$router.push({
                    path: neStep
                })
            },
            ...mapMutations({
                setMerchantInfo: 'SET_MERCHANT_INFO',
                setSecondDirectory: 'SET_SECOND_DIRECTORYs',
                setTabList: 'SET_TAB_LIST'
            }),
        },
        created() {
            this.rsaKey = new RSAKey()
        },
        computed: {
            ...mapGetters([
                'secondDirectory'
            ])
        }
    }
</script>

<style rel="stylesheet/scss" lang="scss">
    $bg:#2d3a4b;
    $light_gray:#eee;
    $dark_gray:#889aa4;

    .login-container {
        position: fixed;
        height: 100%;
        width: 100%;
        background-color: $bg;
        .el-input {
            display: inline-block;
            height: 47px;
            width: 85%;
            input {
                background: transparent;
                border: 0px;
                -webkit-appearance: none;
                border-radius: 0px;
                padding: 12px 5px 12px 15px;
                color: $light_gray;
                height: 47px;
                &:-webkit-autofill {
                    -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
                    -webkit-text-fill-color: #fff !important;
                }
            }
        }
        .el-form-item {
            border: 1px solid rgba(255, 255, 255, 0.1);
            background: rgba(0, 0, 0, 0.1);
            border-radius: 5px;
            color: #454545;
        }
        .logo-box {
            left: 50%;
            top: 50%;

            transform: translateY(-260px);
            margin-left: -100px;
            position: absolute;
        }
        .login-form {
            position: absolute;
            left: 0;
            right: 0;
            top: 50%;
            border-radius: 5px;
            transform: translateY(-300px);
            width: 520px;
            padding: 35px 35px 15px 35px;
            margin: 120px auto;
            border: 1px solid #fff;
        }
        .tips {
            font-size: 14px;
            color: #fff;
            margin-bottom: 10px;
            span {
                &:first-of-type {
                    margin-right: 16px;
                }
            }
        }
        .comText {
            color: #fff;
            font-size: 14px;
            text-align: center;
        }
        .svg-container {
            padding: 6px 5px 6px 10px;
            color: $dark_gray;
            vertical-align: middle;
            width: 30px;
            display: inline-block;
            &_login {
                font-size: 20px;
            }
        }
        .title {
            font-size: 22px;
            font-weight: 400;
            color: $light_gray;
            margin: 0px auto 40px auto;
            text-align: center;
            letter-spacing: 3px
        }
        .show-pwd {
            position: absolute;
            right: 10px;
            top: 7px;
            font-size: 16px;
            color: $dark_gray;
            cursor: pointer;
            user-select: none;
        }
    }
</style>
